package com.mantru.iotpot.Cook;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.Layout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AlignmentSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.DateClass.Handing_Config;
import com.mantru.iotpot.Home.HomeActivity;
import com.mantru.iotpot.MakeSeekBar;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Tools.LoadingDialogUtil;
import com.mantru.iotpot.Tools.tools;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.eventbus.EventMessage;
import com.mantru.iotpot.eventbus.RefreshEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;



public class ManualCookActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {
    private ApplicationClass ac;
    private SeekBar seekBar1;
    private MakeSeekBar customSeekBar;
    private LinearLayout back;
    private Button wendu;
    private Button rotation1;
    private Button rotation2;
    private Button rotation3;
    private TextView name1;
    private TextView name2;
    private TextView name3;
    private TextView name4;
    private TextView name5;
    private TextView name6;
    private TextView text1;
    private TextView text2;
    private TextView text3;
    private TextView text4;
    private TextView text5;
    private TextView text6;
    private List<Handing_Config> list = new ArrayList<>();
    private Handler handler = new Handler(); ; // 用于定时任务
    private AlertDialog dialog; // 用于存储弹窗对象
    private Runnable runnable; // 用于计时器逻辑
    private int progress1 = 0;//火力挡位 0-9档
    private int progress2 = 0;//转速 0-5档
    private int position = 1;//机械臂位置 1放下、2抬起
    private int rotation = 0;//揽拌子转向：0顺时针、1逆时针、2正反转
    private LinearLayout up;
    private LinearLayout down;
    private ImageView img1;
    private ImageView img2;
    private ImageView img3;
    private ImageView img4;
    private Button box1;
    private Button box2;
    private Button box3;
    private Button box4;
    private FrameLayout potPosition1;
    private FrameLayout potPosition2;
    private FrameLayout potPosition3;
    private int selectbox = 1;
    private LinearLayout way1;
    private LinearLayout way2;
    private LinearLayout way3;
    private LinearLayout way4;
    private LinearLayout way5;
    private LinearLayout way6;
    private Button putfood;
    private Button restbox;
    private LinearLayout lock;
    private LinearLayout locks;
    private ImageView jiantou;
    private TextView lock_text1;
    private TextView lock_text2;
    private ImageView background;
    private View.OnTouchListener touchListener;
    private View.OnTouchListener sontouchListener;
    private CountDownTimer timer;
    private ImageView lockBackground;
    private ColorStateList normalColor;
    private ColorStateList minColor;
    private Button wendu_error;
    private Dialog dialog1;
    private int cheak = 3;//当前锅位置：1洗锅位、2出菜位、3炒菜位
    private int ErrorGripper = 0;//0表示机械臂没有故障，1表示机械臂出现故障
    private String TAG = "ManualCookActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main8);
        ac = (ApplicationClass) getApplication();// 初始化 ApplicationClass
        normalColor = ContextCompat.getColorStateList(ManualCookActivity.this, R.color.normal_seekbar_color); // 正常颜色
        minColor = ContextCompat.getColorStateList(ManualCookActivity.this, R.color.min_seekbar_color);// 最小值颜色
        boolean result = ac.Handing_Start();
        Log.d("ManualCookActivity","result: " + result);
        initialization(); // 初始化按钮
        getJson(); // 获取json数据
        Log.d("getJson", "json_data获取成功");
        setview(); // 设置控件文本
        if (result){
            cheak(); // 初始化状态
            Log.d("ManualCookActivity","cheak完成");
            startcheak(); // 定时任务
        }

    }

    public void initialization(){
        seekBar1 = findViewById(R.id.seekBar1);
        customSeekBar = findViewById(R.id.seekbar2);
        back = findViewById(R.id.work_back);
        wendu = findViewById(R.id.work_button1);
        wendu_error = findViewById(R.id.work_error);
        rotation1 = findViewById(R.id.way_rotation1);//搅拌方向
        rotation2 = findViewById(R.id.way_rotation2);
        rotation3 = findViewById(R.id.way_rotation3);
        name1 = findViewById(R.id.way_name1);//组合名字
        name2 = findViewById(R.id.way_name2);
        name3 = findViewById(R.id.way_name3);
        name4 = findViewById(R.id.way_name4);
        name5 = findViewById(R.id.way_name5);
        name6 = findViewById(R.id.way_name6);
        text1 = findViewById(R.id.way_text1);//组合内容
        text2 = findViewById(R.id.way_text2);
        text3 = findViewById(R.id.way_text3);
        text4 = findViewById(R.id.way_text4);
        text5 = findViewById(R.id.way_text5);
        text6 = findViewById(R.id.way_text6);
        up = findViewById(R.id.way_up);
        down = findViewById(R.id.way_down);
        img1 = findViewById(R.id.work_img1);//料盒投发图片
        img2 = findViewById(R.id.work_img3);
        img3 = findViewById(R.id.work_img5);
        img4 = findViewById(R.id.work_img7);
        box1 = findViewById(R.id.cook_box1);//料盒投放按钮
        box2 = findViewById(R.id.cook_box2);
        box3 = findViewById(R.id.cook_box3);
        box4 = findViewById(R.id.cook_box4);
        potPosition1 = findViewById(R.id.PotPosition1);//锅位
        potPosition2 = findViewById(R.id.PotPosition2);
        potPosition3 = findViewById(R.id.PotPosition3);
        way1 = findViewById(R.id.way1);//组合按钮
        way2 = findViewById(R.id.way2);
        way3 = findViewById(R.id.way3);
        way4 = findViewById(R.id.way4);
        way5 = findViewById(R.id.way5);
        way6 = findViewById(R.id.way6);
        putfood = findViewById(R.id.putfood);
        restbox = findViewById(R.id.ResetBox);
        lock = findViewById(R.id.work_lock);
        locks = findViewById(R.id.work_locks);
        jiantou = findViewById(R.id.jiantou);
        lock_text1 = findViewById(R.id.lock_text1);
        lock_text2 = findViewById(R.id.lock_text2);
        background = findViewById(R.id.background);
        lockBackground = findViewById(R.id.lock_background);

        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {//火力
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // progress参数即为当前的进度值
                if (progress < 1) {
                    progress = 1; // 设置最小值为1
                    seekBar1.setProgress(1);
                }
                // 根据进度切换颜色
                if (progress == 1) {
                    seekBar.setProgressTintList(minColor); // 设置为最小值颜色
                } else {
                    seekBar.setProgressTintList(normalColor); // 设置为正常颜色
                }
                progress1 = progress - 1;
                Log.d("progress","progress1: " + progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 开始拖动时的操作
                ac.Handing_Setting_Fire(progress1);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 停止拖动时的操作
                ac.Handing_Setting_Fire(progress1);
            }
        });
        customSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {//转速
               // 最小值颜色
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (progress < 1) {
                    progress = 1; // 设置最小值为1
                    customSeekBar.setProgress(1);
                }
                // 根据进度切换颜色
                if (progress == 1) {
                    seekBar.setProgressTintList(minColor); // 设置为最小值颜色
                } else {
                    seekBar.setProgressTintList(normalColor); // 设置为正常颜色
                }
                progress2 = progress - 1;
                Log.d("progress","progress2: " + progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                ac.Handing_Setting_Gripper(1, rotation, progress2);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                ac.Handing_Setting_Gripper(1, rotation, progress2);
            }
        });
        back.setOnClickListener(this);
        rotation1.setOnClickListener(this);//搅拌爪方向
        rotation2.setOnClickListener(this);
        rotation3.setOnClickListener(this);
        up.setOnClickListener(this);//抬起/放下搅拌爪
        down.setOnClickListener(this);
        box1.setOnClickListener(this);//料盒
        box2.setOnClickListener(this);
        box3.setOnClickListener(this);
        box4.setOnClickListener(this);
        way1.setOnClickListener(this);
        way2.setOnClickListener(this);
        way3.setOnClickListener(this);
        way4.setOnClickListener(this);
        way5.setOnClickListener(this);
        way6.setOnClickListener(this);
        putfood.setOnClickListener(this);
        restbox.setOnClickListener(this);
        potPosition1.setOnClickListener(this);//锅位
        potPosition2.setOnClickListener(this);
        potPosition3.setOnClickListener(this);
        lock.setOnClickListener(this);
        locks.setOnClickListener(this);
        way1.setOnLongClickListener(this);//长按事件
        way2.setOnLongClickListener(this);
        way3.setOnLongClickListener(this);
        way4.setOnLongClickListener(this);
        way5.setOnLongClickListener(this);
        way6.setOnLongClickListener(this);
    }

    public void getJson(){//获取json数据
        String json_data = ac.GetSQLData_Handing_Config(1);
        Log.d("getJson","json_data: " + json_data);
        try {
            // 将字符串转换为 JSONObject
            JSONObject jsonObject = new JSONObject(json_data);
            boolean success = jsonObject.getBoolean("success");
            int itemCount = jsonObject.getInt("item_count");
            JSONArray itemData = jsonObject.getJSONArray("item_data");

            Log.d("getJson", "success: " + success);
            Log.d("getJson", "item_count: " + itemCount);

            // 遍历 item_data 数组
            for (int i = 0; i < itemData.length(); i++) {
                JSONObject item = itemData.getJSONObject(i);
                String configId = item.getString("config_id");
                String name = item.getString("name");
                String text = item.getString("text");

                Log.d("getJson", "item " + i + " - config_id: " + configId);
                Log.d("getJson", "item " + i + " - name: " + name);
                Log.d("getJson", "item " + i + " - text: " + text);
                list.add(new Handing_Config(configId,name,text));
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("JSONParse", "Error parsing JSON: " + e.getMessage());
        }
    }

    //设置喷泵内的文本
    public void setview() {
        for (Handing_Config handingConfig : list) {
            String configId = handingConfig.getConfig_id();
            String name = handingConfig.getName();
            String text = handingConfig.getText();
            Log.d("Handing_Config","text: " + text);
            // 处理 text 字段，将 / 替换为换行符，并限制显示最多三行
            SpannableString processedText = processText(text);
            if (configId.equals("1")) {
                Log.d("text1","text1: " + text);
                name1.setText(name);
                text1.setText(text);
            } else if (configId.equals("2")) {
                name2.setText(name);
                text2.setText(text);
            } else if (configId.equals("3")) {
                name3.setText(name);
                text3.setText(text);
            } else if (configId.equals("4")) {
                name4.setText(name);
                text4.setText(processedText);
            } else if (configId.equals("5")) {
                name5.setText(name);
                text5.setText(processedText);
            } else if (configId.equals("6")) {
                name6.setText(name);
                text6.setText(processedText);
            }
        }
    }

    private SpannableString processText(String text) {
        // 将 / 替换为换行符
        String replacedText = text.replace("/", "\n");
        // 按换行符分割
        String[] lines = replacedText.split("\n");
        // 如果行数超过 3 行，截取前 3 行并添加省略号
        if (lines.length > 3) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 3; i++) {
                sb.append(lines[i]).append("\n");
            }
            sb.append("...");
            replacedText = sb.toString();
        }

        // 创建 SpannableString
        SpannableString spannableString = new SpannableString(replacedText);

        // 设置每一行居中对齐
        spannableString.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        return spannableString;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.work_back){//返回按钮
            back.setBackgroundResource(R.drawable.button13);
            // 返回按钮
            String title = "询问";
            String content = "确认要终止炒菜吗？";
            tools.showCustomDialog(this, title, content, new tools.OnDialogButtonClickListener() {
                @Override
                public void onConfirmClick() {
                    // 点击确认按钮后的逻辑
                    //Toast.makeText(ManualCookActivity.this, "确认", Toast.LENGTH_SHORT).show();
                    boolean result = ac.CheckIsCanClose();
                    if (result){
//                        ToastUtils.show(ManualCookActivity.this, "确认");
                        back.setBackgroundResource(R.drawable.button11);
                        ac.Handing_Stop();
                        LoadingDialogUtil.showLoadingDialog(ManualCookActivity.this);
                        finish();
                    }else {
                        ToastUtils.show(ManualCookActivity.this, "点击运动中");
                    }
                }

                @Override
                public void onCancelClick() {
                    // 点击取消按钮后的逻辑
                    //Toast.makeText(ManualCookActivity.this, "取消", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(ManualCookActivity.this, "取消");
                    back.setBackgroundResource(R.drawable.button11);
                }
            });
        } else if (v.getId() == R.id.way_rotation1) {//揽拌子转向：0正方向、1反方向、2周期正反转
            rotation = 0;
            ac.Handing_Setting_Gripper(1, rotation, progress2);
            cleanbutton(1);
            rotation1.setBackgroundResource(R.drawable.button13);
        }else if (v.getId() == R.id.way_rotation2) {
            rotation = 1;
            ac.Handing_Setting_Gripper(1, rotation, progress2);
            cleanbutton(1);
            rotation2.setBackgroundResource(R.drawable.button13);
        }else if (v.getId() == R.id.way_rotation3) {
            rotation = 2;
            ac.Handing_Setting_Gripper(1, rotation, progress2);
            cleanbutton(1);
            rotation3.setBackgroundResource(R.drawable.button13);
        } else if (v.getId() == R.id.way_up) {//机械臂位置 1放下、2抬起
            String str = ac.CheckIsCanMove("抬起");
            if (str.length() > 0) {
                //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                ToastUtils.show(this,str);
                return;
            }
            position = 2;
            cleanbutton(2);
            up.setBackgroundResource(R.drawable.button12);
            // 将 seekbar2 的值设置为 0
            customSeekBar.setProgress(1);
            progress2 = 0; // 同时更新 progress2 的值
            rotation = 0;//爪子方向改为顺时针
            ac.Handing_Setting_Gripper(2, rotation, progress2);
            customSeekBar.setEnabled(false);
            if (ac.gripper_position_value == 1) {//机械臂放下
                if (ErrorGripper == 1) {
                    ShowCheakDialog();
                }
                ErrorGripper = 0;
            }

        } else if (v.getId() == R.id.way_down) {
            customSeekBar.setEnabled(true);
            String str = ac.CheckIsCanMove("放下");
            if (str.length() > 0) {
                //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                ToastUtils.show(this,str);
                return;
            }
            position = 1;
            ac.Handing_Setting_Gripper(1, rotation, progress2);
            cleanbutton(2);
            down.setBackgroundResource(R.drawable.button12);
        } else if (v.getId() == R.id.PotPosition1) {//锅位置：1洗锅位、2出菜位、3炒菜位
            String str = ac.CheckIsCanMove("出菜");
            if (str.length() > 0) {
                //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                ToastUtils.show(this,str);
                return;
            }
            ac.Handing_Setting_PotPosition(2);
            ac.SaveLog("点击了出菜按钮");
            cleanbutton(3);
            potPosition1.setBackgroundResource(R.drawable.button13);
            //将火力设置为0
            seekBar1.setProgress(1);
            progress1 = 0;
            seekBar1.setProgressTintList(minColor); // 设置为最小值颜色
            ac.Handing_Setting_Fire(progress1);//火力
            //将转速设置为0
            customSeekBar.setProgress(1);
            progress2 = 0;
            rotation = 0;
            customSeekBar.setProgressTintList(minColor);// 设置为最小值颜色
//            ac.Handing_Setting_Gripper(2, rotation, progress2);
            //点击出菜位按钮时，禁止整个页面
            lockBackground.setVisibility(View.VISIBLE);
            if (cheak == 3){
                if(ac.gripper_position_value == 1){//机械臂放下
                    if (ErrorGripper == 1){
                        ShowCheakDialog();
                        ErrorGripper = 0;
                    }
                }
            }
            cheak = 2;
        }else if (v.getId() == R.id.PotPosition2) {//锅位置：1洗锅位、2出菜位、3炒菜位
            String str = ac.CheckIsCanMove("洗锅");
            if (str.length() > 0) {
                //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                ToastUtils.show(this,str);
                return;
            }
            //将火力和转速设置为0
            seekBar1.setProgress(1);
            progress1 = 0;
            seekBar1.setProgressTintList(minColor); // 设置为最小值颜色
            ac.Handing_Setting_Fire(progress1);//火力
            //将转速设置为0
            customSeekBar.setProgress(1);
            progress2 = 0;
            rotation = 0;
            customSeekBar.setProgressTintList(minColor);// 设置为最小值颜色
//            ac.Handing_Setting_Gripper(2, rotation, progress2);
            //洗锅
            ac.Handing_Setting_PotPosition(1);
            ac.SaveLog("点击了洗锅按钮");
            cleanbutton(3);
            potPosition2.setBackgroundResource(R.drawable.button13);
            //点击出菜位按钮时，禁止整个页面
            lockBackground.setVisibility(View.VISIBLE);
            if (cheak == 3){
                if(ac.gripper_position_value == 1){//机械臂放下
                    if (ErrorGripper == 1){
                        ShowCheakDialog();
                        ErrorGripper = 0;
                    }
                }
            }
            cheak = 1;
        }else if (v.getId() == R.id.PotPosition3) {//锅位置：1洗锅位、2出菜位、3炒菜位
            String str = ac.CheckIsCanMove("炒菜");
            if (str.length() > 0) {
                //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                ToastUtils.show(this,str);
                return;
            }
            //将火力和转速设置为0
            seekBar1.setProgress(1);
            progress1 = 0;
            seekBar1.setProgressTintList(minColor); // 设置为最小值颜色
            ac.Handing_Setting_Fire(progress1);//火力
            //将转速设置为0
            customSeekBar.setProgress(1);
            progress2 = 0;
            rotation = 0;
            customSeekBar.setProgressTintList(minColor);// 设置为最小值颜色
//            ac.Handing_Setting_Gripper(1, rotation, progress2);
            ac.Handing_Setting_PotPosition(3);
            ac.SaveLog("点击了炒菜按钮");
            cleanbutton(3);
            potPosition3.setBackgroundResource(R.drawable.button13);
            cheak = 3;
        } else if (v.getId() == R.id.cook_box1) {//料盒投放
            if (selectbox == 1){
                String str = ac.CheckIsCanMove("投料");
                Log.d("Manual","str " + str);
                if (str.length() > 0) {
                    //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this,str);
                    return;
                }
                ac.Handing_Setting_ThrowBox(1,1);
                img2.setImageResource(R.drawable.select);
                box1.setVisibility(View.INVISIBLE);
                box2.setVisibility(View.VISIBLE);
                selectbox = 2;
            }
        }else if (v.getId() == R.id.cook_box2) {
            if (selectbox == 2){
                String str = ac.CheckIsCanMove("投料");
                if (str.length() > 0) {
                    //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this,str);
                    return;
                }
                ac.Handing_Setting_ThrowBox(2,1);
                img3.setImageResource(R.drawable.select);
                box2.setVisibility(View.INVISIBLE);
                box3.setVisibility(View.VISIBLE);
                selectbox = 3;
            }
        }else if (v.getId() == R.id.cook_box3) {
            if (selectbox == 3){
                String str = ac.CheckIsCanMove("投料");
                if (str.length() > 0) {
                    //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this,str);
                    return;
                }
                ac.Handing_Setting_ThrowBox(3,1);
                img4.setImageResource(R.drawable.select);
                box3.setVisibility(View.INVISIBLE);
                box4.setVisibility(View.VISIBLE);
                selectbox = 4;
            }
        }else if (v.getId() == R.id.cook_box4) {
            if (selectbox == 4){
                String str = ac.CheckIsCanMove("投料");
                if (str.length() > 0) {
                    //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this,str);
                    return;
                }
                ac.Handing_Setting_ThrowBox(4,1);
                box4.setVisibility(View.INVISIBLE);
            }
        } else if (v.getId() == R.id.way1) {//油泵
            Log.d("ppp", "way1 clicked");
            ac.Handing_Setting_OpenNozzle(1,1);
        }else if (v.getId() == R.id.way2) {
            ac.Handing_Setting_OpenNozzle(2,1);
        }else if (v.getId() == R.id.way3) {
            ac.Handing_Setting_OpenNozzle(3,1);
        }else if (v.getId() == R.id.way4) {
            ac.Handing_Setting_OpenNozzle(4,1);
        }else if (v.getId() == R.id.way5) {
            ac.Handing_Setting_OpenNozzle(5,1);
        }else if (v.getId() == R.id.way6) {
            ac.Handing_Setting_OpenNozzle(6,1);
        } else if (v.getId() == R.id.putfood) {//投菜方式
//            Toast.makeText(this, "此功能还在开发中", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, ThrowVegetablesActivity.class);
            intent.putExtra("type",1);
            startActivity(intent);
        } else if (v.getId() == R.id.ResetBox) {//料盒复位
            ac.Handing_Setting_ResetBox();
            cleanbutton(4);
            selectbox = 1;
        }
        if (v.getId() == R.id.work_lock) {
            background.setVisibility(View.VISIBLE);
            locks.setVisibility(View.VISIBLE);
            jiantou.setVisibility(View.VISIBLE);
            lock_text1.setVisibility(View.VISIBLE);
            lock_text2.setVisibility(View.VISIBLE);
            initialization();
        }else if (v.getId() == R.id.work_locks) {
            background.setVisibility(View.GONE);
            locks.setVisibility(View.GONE);
            jiantou.setVisibility(View.GONE);
            lock_text1.setVisibility(View.GONE);
            lock_text2.setVisibility(View.GONE);
            initialization();
        }
    }

    private void startcheak() {
        if (handler != null) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // 执行的任务：读取数据并更新 UI
                    cheak();
                    // 递归调用，实现每秒重复执行
                    handler.postDelayed(this, 1000);
                }
            }, 1000); // 延迟1秒执行
        } else {
            Log.e("ManualCookActivity", "Handler is null in startcheak method");
        }
    }

    @Override
    protected void onDestroy() {
        // 移除所有回调，避免内存泄漏
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        // 关闭弹窗
        dismissDialog();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void cheak() {
        // 确保在 UI 线程中更新
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int status = ac.handmaster.steep_status; // 读取状态
                Log.d("ManualCookActivity","status: " + status);
                if (ac.pot_temperature_is_error == true){
                    wendu.setVisibility(View.INVISIBLE);
                    wendu_error.setVisibility(View.VISIBLE);
                }else {
                    wendu_error.setVisibility(View.GONE);
                    wendu.setVisibility(View.VISIBLE);
                    String temperature = String.valueOf(ac.pot_temperature_value); // 读取温度
                    Log.d("wendu", "温度: " + temperature);
                    wendu.setText("锅温：" + temperature + "℃");
                }
                Log.d("CookActivity", "UI updated.");
                if (status == 0){
                    showDialog();
                } else {
                    dismissDialog();
                }
            }
        });
    }

    private void showDialog() {
        // 如果弹窗已经显示，则不重复显示
        if (dialog != null && dialog.isShowing()) {
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.waitcook, null);
        builder.setView(dialogView);

        // 获取弹窗中的按钮和计时器文本
        final TextView countdownTextView = dialogView.findViewById(R.id.countdownTextView);
        timer = new CountDownTimer(60 * 1000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                countdownTextView.setText((millisUntilFinished / 1000) + "S");
            }
            @Override
            public void onFinish() {
                // 如果弹窗存在且正在显示，则关闭它
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if ( timer != null ){
                    timer.cancel();
                    timer = null;
                }
                finish();
                //Toast.makeText(ManualCookActivity.this,"设备就位失败，请重试！",Toast.LENGTH_SHORT).show();
                ToastUtils.show(ManualCookActivity.this,"设备就位失败，请重试！");
                ac.Handing_Stop();
            }
        };
        timer.start();
        // 创建并显示弹窗
        dialog = builder.create();
        dialog.show();
        // 关键代码：设置窗口背景透明
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        // 关键代码：设置点击外部不可取消
        dialog.setCanceledOnTouchOutside(false);
        // 保存计时器和弹窗引用，以便在状态改变时停止计时器和关闭弹窗
        this.dialog = dialog;
        this.handler = handler;
        this.runnable = runnable;
    }

    // 关闭弹窗
    private void dismissDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            if ( timer != null ){
                timer.cancel();
                timer = null;
            }
        }
    }

    public void cleanbutton(int type){
        if (type == 1){//搅拌爪方向
            rotation1.setBackgroundResource(R.drawable.button14);
            rotation2.setBackgroundResource(R.drawable.button14);
            rotation3.setBackgroundResource(R.drawable.button14);
        } else if (type == 2) {//抬起/放下搅拌爪
            up.setBackgroundResource(R.drawable.button15);
            down.setBackgroundResource(R.drawable.button15);
        } else if (type == 3) {//设置锅位
            potPosition1.setBackgroundResource(R.drawable.button11);
            potPosition2.setBackgroundResource(R.drawable.button11);
            potPosition3.setBackgroundResource(R.drawable.button11);
        } else if (type == 4) {//料盒复位
            img2.setImageResource(R.drawable.noselect);
            img3.setImageResource(R.drawable.noselect);
            img4.setImageResource(R.drawable.noselect);
            box1.setVisibility(View.VISIBLE);
            box2.setVisibility(View.INVISIBLE);
            box3.setVisibility(View.INVISIBLE);
            box4.setVisibility(View.INVISIBLE);
        }
    }

    // 在Activity可见时注册EventBus
    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("ACTION_CLOSE_LOADING_DIALOG"));
    }

    @Override
    protected void onStop(){
        super.onStop();
        EventBus.getDefault().unregister(this);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage event){
        Log.d("onEventBusMessage","position: " + position + " rotation: " + rotation + "/n id: " + event.id + " msg: " + event.message);
        if (event.id == EventMessage.MSG_ID_OnGripperChange){//机械臂位置发生变化
            String jsonString = event.message;
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                String oldValue = jsonObject.getString("old_value");//旧的状态
                String newValue = jsonObject.getString("new_value");//新的状态
                if (newValue.equals("1")){//放下
                    up.setBackgroundResource(R.drawable.button15);
                    down.setBackgroundResource(R.drawable.button12);
                    up.setEnabled(true);
                    down.setEnabled(false);
                    rotation1.setEnabled(true);
                    rotation2.setEnabled(true);
                    rotation3.setEnabled(true);
                    potPosition1.setEnabled(true);
                    potPosition2.setEnabled(true);
                    potPosition3.setEnabled(true);
                    customSeekBar.setProgress(1);
                    progress2 = 0;
                    rotation1.setBackgroundResource(R.drawable.button13);
                    customSeekBar.setEnabled(true);
                } else if (newValue.equals("2")) {//抬起
                    down.setBackgroundResource(R.drawable.button15);
                    up.setBackgroundResource(R.drawable.button12);
                    down.setEnabled(true);
                    up.setEnabled(false);
                    rotation1.setEnabled(false);
                    rotation2.setEnabled(false);
                    rotation3.setEnabled(false);
                    potPosition1.setEnabled(true);
                    potPosition2.setEnabled(true);
                    potPosition3.setEnabled(true);
                    customSeekBar.setProgress(1);
                    progress2 = 0;
                    rotation1.setBackgroundResource(R.drawable.button14);
                    rotation2.setBackgroundResource(R.drawable.button14);
                    rotation3.setBackgroundResource(R.drawable.button14);
                    customSeekBar.setEnabled(false);
                }
            }catch (JSONException e) {
                e.printStackTrace();
                Log.e("EventBus", "Error parsing JSON: " + e.getMessage());
            }
        } else if (event.id == EventMessage.MSG_ID_OnPotChange) {//锅位置发生变化
            String jsonString = event.message;
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                String newValue = jsonObject.getString("new_value");//新的状态
                switch ( newValue ){
                    case "1"://洗锅位
                        //洗锅位按钮亮起
                        potPosition1.setBackgroundResource(R.drawable.button14);
                        potPosition2.setBackgroundResource(R.drawable.button13);
                        potPosition3.setBackgroundResource(R.drawable.button14);
//                        ac.Handing_Setting_PotPosition(1);
                        //顺时针逆时针正反转不能动
                        rotation1.setEnabled(false);
                        rotation2.setEnabled(false);
                        rotation3.setEnabled(false);
                        customSeekBar.setProgress(1);
                        progress2 = 0;
                        rotation1.setBackgroundResource(R.drawable.button14);
                        rotation2.setBackgroundResource(R.drawable.button14);
                        rotation3.setBackgroundResource(R.drawable.button14);
                        customSeekBar.setEnabled(false);
                        break;
                    case "2"://出菜位
                        //出菜位按钮亮起
                        potPosition1.setBackgroundResource(R.drawable.button13);
                        potPosition2.setBackgroundResource(R.drawable.button14);
                        potPosition3.setBackgroundResource(R.drawable.button14);
//                        ac.Handing_Setting_PotPosition(2);
                        //顺时针逆时针正反转不能动
                        rotation1.setEnabled(false);
                        rotation2.setEnabled(false);
                        rotation3.setEnabled(false);
                        customSeekBar.setProgress(1);
                        progress2 = 0;
                        rotation1.setBackgroundResource(R.drawable.button14);
                        rotation2.setBackgroundResource(R.drawable.button14);
                        rotation3.setBackgroundResource(R.drawable.button14);
                        customSeekBar.setEnabled(false);
                        break;
                    case "3"://炒菜位
                        //炒菜位按钮亮起
                        potPosition1.setBackgroundResource(R.drawable.button14);
                        potPosition2.setBackgroundResource(R.drawable.button14);
                        potPosition3.setBackgroundResource(R.drawable.button13);
//                        ac.Handing_Setting_PotPosition(3);
                        //顺时针逆时针正反转可以动
                        rotation1.setEnabled(true);
                        rotation2.setEnabled(true);
                        rotation3.setEnabled(true);
                        customSeekBar.setProgress(1);
                        progress2 = 0;
                        rotation1.setBackgroundResource(R.drawable.button13);
                        rotation2.setBackgroundResource(R.drawable.button14);
                        rotation3.setBackgroundResource(R.drawable.button14);
                        customSeekBar.setEnabled(true);
                        break;
                }

                //手臂状态
                down.setBackgroundResource(R.drawable.button15);
                up.setBackgroundResource(R.drawable.button12);
                down.setEnabled(true);
                up.setEnabled(false);
                //锁屏按钮消失
                lockBackground.setVisibility(View.GONE);
                ac.SaveLog("已接收到锅位运动完成的事件，蒙板消除");
            }catch (JSONException e) {
                e.printStackTrace();
                Log.e("EventBus", "Error parsing JSON: " + e.getMessage());
                ac.SaveLog("已接收到锅位运动完成的事件，蒙板消除出错。原因： " + e.getMessage());
            }
        } else if (event.id == EventMessage.MSG_ID_OnGripperMoving) {
            String jsonString = event.message;
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                String oldValue = jsonObject.getString("old_value");//旧的状态
                String newValue = jsonObject.getString("new_value");//新的状态
                up.setBackgroundResource(R.drawable.button15);
                up.setEnabled(false);
                down.setBackgroundResource(R.drawable.button15);
                down.setEnabled(false);
                rotation1.setBackgroundResource(R.drawable.button14);
                rotation2.setBackgroundResource(R.drawable.button14);
                rotation3.setBackgroundResource(R.drawable.button14);
                rotation1.setEnabled(false);
                rotation2.setEnabled(false);
                rotation3.setEnabled(false);
                potPosition1.setEnabled(false);
                potPosition2.setEnabled(false);
                potPosition3.setEnabled(false);
                customSeekBar.setProgress(1);
                progress2 = 0;
                customSeekBar.setEnabled(false);
            }catch (JSONException e) {
                e.printStackTrace();
                Log.e("EventBus", "Error parsing JSON: " + e.getMessage());
            }
        }else if (event.id == EventMessage.MSG_ID_OnPotMoving) {
            up.setBackgroundResource(R.drawable.button15);
            up.setEnabled(false);
            down.setBackgroundResource(R.drawable.button15);
            down.setEnabled(false);
            rotation1.setBackgroundResource(R.drawable.button14);
            rotation2.setBackgroundResource(R.drawable.button14);
            rotation3.setBackgroundResource(R.drawable.button14);
            rotation1.setEnabled(false);
            rotation2.setEnabled(false);
            rotation3.setEnabled(false);
            customSeekBar.setProgress(1);
            progress2 = 0;
            customSeekBar.setEnabled(false);
        } else if (event.id == EventMessage.MSG_ID_ErrorGripper) {//收到了机械臂出现故障的消息
            ErrorGripper = 1;
            ac.SaveLog(TAG + " 界面接收到机械臂出现故障的事件");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) // 添加 sticky 属性
    public void onRefreshEvent(RefreshEvent event) {
        if (event.getEventType() == RefreshEvent.REFRESH_TEXT) {
            Log.d("RefreshEvent", "sucess");
            getJson(); // 获取最新数据
            setview(); // 更新 UI
            // 移除粘性事件（可选）
//            EventBus.getDefault().removeStickyEvent(event);
        }
    }


    @Override
    public boolean onLongClick(View v) {
        if(v.getId() == R.id.way1){
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",1);
            intent.putExtra("type",1);
            startActivity(intent);
        } else if (v.getId() == R.id.way2) {
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",2);
            intent.putExtra("type",1);
            startActivity(intent);
        }else if (v.getId() == R.id.way3) {
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",3);
            intent.putExtra("type",1);
            startActivity(intent);
        }else if (v.getId() == R.id.way4) {
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",4);
            intent.putExtra("type",1);
            startActivity(intent);
        }else if (v.getId() == R.id.way5) {
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",5);
            intent.putExtra("type",1);
            startActivity(intent);
        }else if (v.getId() == R.id.way6) {
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",6);
            intent.putExtra("type",1);
            startActivity(intent);
        }
        return true;
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("ACTION_CLOSE_LOADING_DIALOG".equals(intent.getAction())) {
                LoadingDialogUtil.closeLoadingDialog();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        // 在界面渲染完成后发送广播关闭弹窗
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                ((ApplicationClass) getApplication()).sendBroadcast("ACTION_CLOSE_LOADING_DIALOG");
            }
        });
    }

    private void ShowCheakDialog(){
        // 如果弹窗已经显示，则不重复显示
        if (dialog1 != null && dialog1.isShowing()) {
            return;
        }
        // 创建自定义对话框
        dialog1 = new Dialog(this);
        dialog1.setContentView(R.layout.manual_cheak_dialog); // 设置对话框的布局

        Button stop = dialog1.findViewById(R.id.manual_cheak_dialog_stop);
        Button low = dialog1.findViewById(R.id.manual_cheak_dialog_low);
        Button rotate = dialog1.findViewById(R.id.manual_cheak_dialog_rotate);

        stop.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_Stop();
            ac.SaveLog("用户点击了炒菜爪手动寻位的停止按钮");
        });

        low.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_Slow();
            ac.SaveLog("用户点击了炒菜爪手动寻位的低速按钮");
        });

        rotate.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_OK();
            ac.SaveLog("用户点击了炒菜爪手动寻位的确认按钮");
            dialog1.dismiss();
        });
        // 关键代码：设置窗口背景透明
        if (dialog1.getWindow() != null) {
            dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }

        dialog1.setCanceledOnTouchOutside(false);

        // 显示对话框
        dialog1.show();
    }
}